package threadjuc;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author zxl
 * @version 1.0
 * @date 2021/10/28 9:03
 * 读写锁
 */
public class Juc12 {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        //写入  必须一个个写入
        for (int i = 0; i < 5; i++) {
            int temp = i;
            new Thread(()->{
                myCache.put(temp+"",temp);
            },String.valueOf(temp)).start();
        }

        //读取  可多个一起读
        for (int i = 0; i < 5; i++) {
            int temp = i;
            new Thread(()->{
                myCache.get(temp+"");
            },String.valueOf(temp)).start();
        }
    }
}
class MyCache{

    Map<String, Object> map = new HashMap<>();

    /**
     * 读写锁
     */
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    /**
     * 写入  必须一个个写入
     * @param key
     * @param value
     */
    public void put(String key,Object value){
        readWriteLock.writeLock().lock();
        try{
            System.out.println(key+"开始写入");
            map.put(key, value);
            System.out.println(key+"写入完毕");
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }

    /**
     * 读取  可多个一起读
     * @param key
     * @return
     */
    public Object get(String key){
        readWriteLock.readLock().lock();
        Object resut = null;
        try{
            System.out.println(key+"开始读取");
            resut = map.get(key);
            System.out.println(key+"读取完毕");
        }finally {
            readWriteLock.readLock().unlock();
        }
        return resut;
    }
}
